﻿using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Wolfy.NetDisk.Core.Model;
using Wolfy.NetDisk.Core.Security;
using Wolfy.NetDisk.Core.Service;
using Wolfy.NetDisk.Site.Models;

namespace Wolfy.NetDisk.Site.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserService userService;
        private readonly IDepartmentService departmentService;
        private readonly ILogService logService;
        private readonly IRoleService roleService;
        private readonly IImageManagerService imageService;

        public AccountController(IUserService userService, IDepartmentService departmentService, ILogService logService, IRoleService roleService, IImageManagerService imageService)
        {
            this.userService = userService;
            this.departmentService = departmentService;
            this.logService = logService;
            this.roleService = roleService;
            this.imageService = imageService;
        }

        private IAuthenticationManager Authentication
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        private void SignInOwin(string name, bool rememberMe, IEnumerable<string> roles)
        {
            var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, name) },
                DefaultAuthenticationTypes.ApplicationCookie,
                    ClaimTypes.Name, ClaimTypes.Role);

            foreach (var role in roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }


            Authentication.SignIn(new AuthenticationProperties
            {
                IsPersistent = rememberMe
            }, identity);
        }
        /// <summary>
        /// get
        /// </summary>
        /// <returns></returns>
        public ActionResult SignIn()
        {
            return View();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SignIn(SignInInput input)
        {
            if (!ModelState.IsValid)
            {
                input.Password = null;
                input.Name = null;
                return View(input);
            }
            //ACHTUNG: remove this in a real app
            var user = userService.Login(input.Name, input.Password);

            if (user == null)
            {
                ModelState.AddModelError("", "用户名或者密码不正确，请重新输入");
                return View();
            }
            SignInOwin(user.UserName, input.Remember, user.Roles.Select(o => o.Name));
            logService.WriteLog(new Log { Conent = "登录", Dt = DateTime.Now, IsDeleted = false, LogType = LogType.Info, Op = "Login", User = user });
            //登录成功 是否是管理员
            if (HttpContext.User.IsInRole("管理员"))
            {
                return RedirectToAction("home", "Manager");
            }
            return RedirectToAction("home", "netdisk");
        }

        public ActionResult SignOff()
        {
            Authentication.SignOut();
            return RedirectToAction("SignIn", "Account");
        }
        /// <summary>
        /// 创建部门下拉列表
        /// </summary>
        /// <returns></returns>
        private IList<SelectListItem> BuildSelectListItemOfDepartment()
        {  //加载页面时 加载部门列表
            var departments = departmentService.Where(o => !o.IsDeleted && o.ParentDepartment.Id > 0);
            List<SelectListItem> lst = new List<SelectListItem>();
            foreach (var item in departments)
            {
                lst.Add(new SelectListItem
                {
                    Text = item.Name,
                    Value = item.Id.ToString()
                });
            }
            return lst;
        }
        /// <summary>
        /// 获取所有性别
        /// </summary>
        /// <returns></returns>
        private IList<SelectListItem> BuildSelectListItemOfGenders()
        {
            return new List<SelectListItem>() { 
            new SelectListItem{ Value="1", Text="男"},
            new SelectListItem{ Value="2", Text="女"},
            new SelectListItem{ Value="3", Text="保密"},
            };
        }
        /// <summary>
        /// 绑定下拉列表
        /// </summary>
        private void BindRegisterDropdownList()
        {
            ViewData["genders"] = BuildSelectListItemOfGenders();
            ViewData["departments"] = BuildSelectListItemOfDepartment();
        }
        /// <summary>
        /// 注册视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            BindRegisterDropdownList();
            return View();
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(UserViewModel user)
        {
            //验证字段
            if (!ModelState.IsValid)
            {
                //重新绑定下拉列表
                BindRegisterDropdownList();
                return View(user);
            }
            //验证验证码是否正确
            if (user.VerifyCode.ToLower() != Session["code"].ToString().ToLower())
            {
                BindRegisterDropdownList();
                ModelState.AddModelError("tips", "验证码不正确");
                return View(user);
            }
            //校验用户是否已经存在
            if (userService.IsExist(user.UserName))
            {
                BindRegisterDropdownList();
                ModelState.AddModelError("tips", "该用户名已经存在");
                return View(user);
            }
            User registerUser = null;
            try
            {

                //添加用户
                var role = roleService.Where(o => o.Name == "普通用户", false).FirstOrDefault();
                var departId = Convert.ToInt32(user.Department);
                var department = departmentService.Where(o => o.Id == departId).FirstOrDefault();
                int userId = userService.Create(new User { Gender = (Gender)Convert.ToInt32(user.Gender), Dt = DateTime.Now, Roles = new List<Role>() { role }, UserName = user.UserName, Pwd = AesSecret.EncryptToken(user.Pwd), Department = department, IsDeleted = false });
                registerUser = userService.Get(userId);
                //日志
                logService.WriteLog(new Log { Conent = "注册用户", LogType = LogType.Info, Dt = DateTime.Now, IsDeleted = false, Op = "Register", User = registerUser });
                return RedirectToAction("Home", "Netdisk");
            }
            catch (Exception ex)
            {
                //日志
                logService.WriteLog(new Log { Conent = ex.Message, Dt = DateTime.Now, IsDeleted = false, Op = "Register_err", User = registerUser, LogType = LogType.Error });
                return RedirectToAction("HttpError505", "Error");
            }

        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult GetVerifyCode()
        {
            string code = string.Empty;
            byte[] imageBuffer = imageService.CreateVerifyCode(6, out code);
            Session["code"] = code;
            return File(imageBuffer, "image/jpeg");
        }
        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <returns></returns>
        public ActionResult FogotPassword()
        {
            return View();
        }
    }

}